package com.shujiaotong.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shujiaotong.common.R;
import com.shujiaotong.pojo.Activity;
import com.shujiaotong.service.IActivityService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2024-10-20
 */
@RestController
@RequestMapping("/activity")
@Slf4j
public class ActivityController {

@Autowired
    private IActivityService activityService;

//分页
    @RequestMapping("page")
    public Object page(@RequestParam int page,
                       @RequestParam int pageSize,
                       @RequestParam(required = false,value = "name") String activityName){
//        接收参数
        log.info("当前页:{},页条数:{},活动:{}",page,pageSize,activityName);
//        分页条件
        Page<Activity> activityPage = new Page<>(page,pageSize);
//        查询条件
        LambdaQueryWrapper<Activity> qw = new LambdaQueryWrapper<>();
        qw.like(!StringUtils.isEmpty(activityName),Activity::getActivityName,activityName);

//        分页查询
        activityService.page(activityPage,qw);
//        返回值
        return R.success(activityPage);

    }

//    新建活动
    @PostMapping
    public R save(@RequestBody Activity activity){
        activity.setCreateTime(LocalDate.now());
        boolean save = activityService.save(activity);
        return save?R.success("新增活动成功"):R.error("新增活动失败");
    }

//    删除
    @DeleteMapping
    public R delete(Long id){
        return activityService.removeById(id) ? R.success("删除成功"):R.error("删除失败");
    }

//    根据id查询
    @GetMapping("/{id}")
    public R getById(@PathVariable Long id ){
        log.info("根据id查询活动:{}",id);
        Activity activity = activityService.getById(id);
        return R.success(activity);
    }
//    修改
    @PutMapping
    public R update(@RequestBody Activity activity){
        log.info("修改活动信息:{}",activity);
        boolean update = activityService.updateById(activity);
        return update?R.success("修改成功"):R.error("修改失败");
    }


//    获取所有活动
    @GetMapping("getActivityList")
    public R getActivityList(){
        return R.success(activityService.list());
    }
}
